/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.network.chassis.customgrid;

import java.awt.Color;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;

import twaver.Follower;
import twaver.Node;
import twaver.TUIManager;
import twaver.TWaverConst;

public class Cell extends Follower{
	
	private int rowIndex;
	private int columnIndex;
	
	public Cell(){
		this.init();
	}
	
	public Cell(Object id){
		super(id);
		this.init();
	}
	
	private void init(){
		this.putBorderInsets(-2);
		this.putBorderColor(Color.RED);
		this.putLabelHighlightable(false);
		this.putLabelFont(TUIManager.getDefault10SizeFont());
		this.putLabelPosition(TWaverConst.POSITION_CENTER);
		this.putLabelOrientation(TWaverConst.LABEL_ORIENTATION_RIGHT);
		this.putCustomDraw(true);
		this.putCustomDrawShapeFactory(TWaverConst.SHAPE_RECTANGLE);
		this.putCustomDrawFillColor(Color.LIGHT_GRAY);
		this.putCustomDrawGradientFactory(TWaverConst.GRADIENT_EXTEND_HORIZONTAL);
	}
	
	public int getColumnIndex() {
		return columnIndex;
	}

	public void setColumnIndex(int columnIndex) {
		if(this.columnIndex != columnIndex){
			int oldValue = this.columnIndex;
			this.columnIndex = columnIndex;
			this.firePropertyChange("columnIndex", oldValue, this.columnIndex);
			adjustBounds();
		}
	}

	public int getRowIndex() {
		return rowIndex;
	}

	public void setRowIndex(int rowIndex) {
		if(this.rowIndex != rowIndex){
			int oldValue = this.rowIndex;
			this.rowIndex = rowIndex;
			this.firePropertyChange("rowIndex", oldValue, this.rowIndex);
			adjustBounds();
		}
	}

	protected void hostPropertyChange(PropertyChangeEvent evt) {
		String name = evt.getPropertyName();
		
		if(TWaverConst.PROPERTYNAME_LOCATION.equals(name) ||
			TWaverConst.PROPERTYNAME_WIDTH.equals(name) ||
			TWaverConst.PROPERTYNAME_HEIGHT.equals(name) ||
			"rowCount".equals(name) || "columnCount".equals(name)){

			adjustBounds();
		}
	}
	
    public void adjustBounds(){   
    	Node host = this.getHost();
    	if(host instanceof CustomGrid){
    		CustomGrid grid = (CustomGrid)host;
    		Rectangle rect = grid.getCellRect(this.rowIndex, this.columnIndex);
    		rect.grow(-5, -5);
    		this.setLocation(rect.x, rect.y);
    		this.setSize(rect.width, rect.height);
    	}
    }

}